package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.CheckInConfigMapper;
import com.zzyl.nursing.mapper.ContractMapper;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import springfox.documentation.spring.web.json.Json;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-26
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private BedServiceImpl bedService;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckInSearchDto selectCheckInById(Long id) {
        //传入入住id，先查入住表
        CheckIn checkIn = checkInMapper.selectCheckInById(id);

        //查入住配置表
        LambdaQueryWrapper<CheckInConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CheckInConfig::getCheckInId, checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(wrapper);

        //入住表拿老人id，查老人表
        Elder elder = elderMapper.selectElderById(checkIn.getElderId());
        //解析亲属关系的json
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(elder.getRemark(), ElderFamilyVo.class);

        //老人表拿床位id，查床位表
        Bed bed = bedService.selectBedById(elder.getBedId());

        //拿老人id，查合同表
        LambdaQueryWrapper<Contract> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Contract::getElderId, checkIn.getElderId());
        Contract contract = contractMapper.selectOne(wrapper1);


        CheckInElderVo checkInElderVo = new CheckInElderVo();
        //计算老人年龄
        String birthday = elder.getBirthday();
        LocalDate birthdayTime = LocalDate.parse(birthday);
        LocalDate now = LocalDate.now();
        checkInElderVo.setAge(now.getYear() - birthdayTime.getYear());
        BeanUtils.copyProperties(elder, checkInElderVo);

        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkIn, checkInConfigVo);
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        BeanUtils.copyProperties(bed, checkInConfigVo);

        CheckInSearchDto checkInSearchDto = new CheckInSearchDto();
        checkInSearchDto.setCheckInElderVo(checkInElderVo);
        checkInSearchDto.setCheckInConfigVo(checkInConfigVo);
        checkInSearchDto.setContract(contract);
        checkInSearchDto.setElderFamilyVoList(elderFamilyVoList);


        return checkInSearchDto;
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }


    /**
     * 新增入住
     *
     * @param dto 入住
     * @return 结果
     */
    @Override
    @Transactional
    public void insertCheckIn(CheckInApplyDto dto) {
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        List<ElderFamilyDto> elderFamilyDtoList = dto.getElderFamilyDtoList();
        CheckInContractDto checkInContractDto = dto.getCheckInContractDto();

        //判断当前填入的老人是否已经入住了
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo());
        wrapper.eq(Elder::getStatus, Elder.CHECK_IN_STATUS);
        Elder elder = elderMapper.selectOne(wrapper);
        if (ObjectUtil.isNotEmpty(elder)) {
            throw new RuntimeException("该老人已经入住,请勿重复提交");
        }
        //修改床位表
        Bed bed = setBed(checkInConfigDto);
        //修改老人表
        elder = setElder(checkInElderDto, bed, elderFamilyDtoList);
        //修改入住表
        CheckIn checkIn = setCheckIn(checkInConfigDto, bed, elder);
        //修改入住配置表
        setCheckInConfig(checkInConfigDto, checkIn);
        //修改合同表
        setContract(checkInContractDto, elder);
    }

    //修改床位表
    private Bed setBed(CheckInConfigDto checkInConfigDto) {
        //修改床位状态，查询床位信息返回
        Bed bed = new Bed();
        bed.setId(checkInConfigDto.getBedId());
        bed.setBedStatus(bed.IN_USE_STATUS);
        bedService.update(bed, new LambdaQueryWrapper<Bed>().eq(Bed::getId, checkInConfigDto.getBedId()));
        bed = bedService.selectBedById(checkInConfigDto.getBedId());
        return bed;
    }

    //修改老人表
    private Elder setElder(CheckInElderDto dto, Bed bed, List<ElderFamilyDto> elderDtoList) {
        Elder elder = new Elder();
        BeanUtils.copyProperties(dto, elder);
        elder.setStatus(elder.CHECK_IN_STATUS);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        //插入家人数据
        elder.setRemark(JSONUtil.toJsonStr(elderDtoList));
        elderMapper.insert(elder);
        return elder;
    }

    //修改入住表
    private CheckIn setCheckIn(CheckInConfigDto dto, Bed bed, Elder elder) {
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(dto, checkIn);
        checkIn.setStatus(checkIn.OCCUPIED_STATUS);
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    //修改入住配置表
    private CheckInConfig setCheckInConfig(CheckInConfigDto dto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto, checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
        return checkInConfig;
    }

    //修改合同表
    private void setContract(CheckInContractDto dto, Elder elder) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto, contract);
        if (dto.getSignDate().isBefore(LocalDateTime.now())) {
            contract.setStatus(contract.NOT_IN_EFFECT_STATUS);
        } else {
            contract.setStatus(contract.IN_EFFECT_STATUS);
        }
        //无法调用OCR图像识别拿到合同编号、开始结束时间，故此处造假数据
        contract.setStartDate(LocalDateTime.now());
        contract.setEndDate(LocalDateTime.now());
        contract.setContractNumber(RandomUtil.randomString(10));
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());

        contractMapper.insert(contract);
    }


    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

}
